package org.example.matrix;

public class GenerateMatrix {
    /**
     * 给你一个正整数 n ，生成一个包含 1 到 n2 所有元素，且元素按顺时针顺序螺旋排列的 n x n 正方形矩阵 matrix 。
     * @param n
     * @return
     */
    public int[][] generateMatrix(int n) {
        //模拟，顺时针遍历数组，每次出界或者已经写过的地方进行一次顺时针转向即可
        int[][] ret = new int[n][n];
        int row =0,col = 0;
        int[][] direction = {{0,1},{1,0},{0,-1},{-1,0}};
        int directionIndex = 0;
        boolean[][] visited = new boolean[n][n];
        for(int i = 1; i<=n*n; i++){
            ret[row][col] = i;
            visited[row][col] = true;

            int nextRow = row + direction[directionIndex][0];
            int nextCol = col + direction[directionIndex][1];
            if(nextRow < 0 || nextRow >=n || nextCol < 0 || nextCol >=n ||
                    visited[nextRow][nextCol]){
                directionIndex = (directionIndex+1)%4;
            }
            row = row + direction[directionIndex][0];
            col = col + direction[directionIndex][1];
        }
        return ret;
    }
}
